//
//  LiveContentView.swift
//  HinsLive
//
//  Created by haoxian on 2019/5/5.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit
import RxSwift


class LiveContentView: UIView {

    let masterInfoView = MasterInfoView()
    
    private(set) lazy var messagesView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 40
        tableView.allowsSelection = false
        tableView.bounces = false
        tableView.register(ChatMessageCell.self, forCellReuseIdentifier: "\(LiveViewController.self)")
        return tableView
    }()
    
    private(set) lazy var chatBtn: RoomIconButton = {
        let btn = RoomIconButton(imageFrame: CGRect(x: 12, y:14, width: 24, height: 24))
        btn.backgroundColor = .roomGrayBackgroundColor
        btn.layer.cornerRadius = 24
        btn.layer.masksToBounds = true
        btn.setImage(R.image.room_btn_chat(), for: .normal)
        btn.setImage(R.image.room_btn_chat(), for: .highlighted)
        btn.rx.tap.subscribe(onNext: { [weak self] _ in
            self?.chatToolView.chatTV.becomeFirstResponder()
        })
        .disposed(by: bag)
        return btn
    }()
    
    private(set) lazy var chatToolView = ChatToolView()
    
    private let bag = DisposeBag()
    
    init(masterName: String, avatarUrl: String) {
        super.init(frame: .zero)
        setupUI()
        masterInfoView.setInfo(masterName: masterName, avatarUrl: avatarUrl)
        chatToolView.chatTV.rx.text
            .distinctUntilChanged()
            .map { [weak self] _ -> CGFloat in
                let height = self?.chatToolView.chatTV.contentSize.height ?? 0
                return height > 44 ? min(height, 80) : 44
            }
            .subscribe(onNext: { [weak self] height in
                guard let self = self else { return }
                self.chatToolView.snp.updateConstraints({ (make) in
                    make.height.equalTo(height)
                })
                self.layoutIfNeeded()
            })
            .disposed(by: bag)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(masterInfoView)
        masterInfoView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalTo(safeAreaLayoutGuide.snp.top).offset(20)
            make.height.equalTo(50)
            make.width.equalTo(170)
        }
        addSubview(chatBtn)
        chatBtn.snp.makeConstraints { (make) in
            make.width.height.equalTo(48)
            make.right.equalToSuperview().offset(-20)
            make.bottom.equalTo(safeAreaLayoutGuide.snp.bottom).offset(-20)
        }
        addSubview(chatToolView)
        chatToolView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
            make.bottom.equalTo(snp.bottom).offset(44)
        }
        addSubview(messagesView)
        messagesView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalTo(chatBtn.snp.left).offset(-20)
            make.bottom.equalTo(chatBtn.snp.bottom)
            make.height.equalTo(200)
        }
    }
    
    func displayChatTool(_ kbFrame: CGRect, _ duration: TimeInterval) {
        var height = chatToolView.chatTV.contentSize.height
        height = height > 44 ? min(height, 80) : 44
        chatToolView.snp.remakeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(height)
            make.bottom.equalTo(snp.bottom).offset(-kbFrame.height)
        }
        let topY: CGFloat = safeAreaInsets.top + 20.0 + 50.0 + 10.0 + 36.0
        let bottomY: CGFloat = kbFrame.origin.y - height - 10.0
        let messagesViewHeight = min(bottomY - topY, 200)
        messagesView.snp.remakeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalTo(chatBtn.snp.left).offset(-20)
            make.bottom.equalTo(chatToolView.snp.top).offset(-10)
            make.height.equalTo(messagesViewHeight)
        }
        UIView.animate(withDuration: duration) {
            self.chatBtn.alpha = 0
            self.layoutIfNeeded()
        }
    }
    
    func hideChatTool(_ kbFrame: CGRect, _ duration: TimeInterval) {
        chatToolView.snp.remakeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
            make.bottom.equalTo(snp.bottom).offset(44)
        }
        messagesView.snp.remakeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalTo(chatBtn.snp.left).offset(-20)
            make.bottom.equalTo(chatBtn.snp.bottom)
            make.height.equalTo(200)
        }
        UIView.animate(withDuration: duration) {
            self.chatBtn.alpha = 1
            self.layoutIfNeeded()
        }
    }
    
    func messagesViewScrollTo(_ indexPath: IndexPath) {
        messagesView.scrollToRow(at: indexPath, at: .bottom, animated: true)
    }
}
